package com.qf.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 创建一个过滤器
 *
 *              Filter:Web三大组件之一:Servlet,Filter,Listener  :前两个重点
 *                      web容器通过反射创建组件(对象)
 *
 *                  生命周期:
 *                          初始化---过滤执行----过滤终止(死亡)
 *                          init(FilterConfig config):默认的初始化时机:web容器启动时被创建
 *                                  参数FilterConfig:过滤器的初始化配置信息
 *
 *                          //过滤完成的任务
 *                          doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
 *                              参数1:
 *                                  req:请求
 *                               参数2:
 *                                  resp:响应对象
 *
 *                                  将req和resp:转成子接口HttpServletRequest  / HttpServletResponse
 *
 *                                参数3:FilterChain:过滤链 接口
 *                                      自己过滤链的规则
 *                                              完成过滤任务后,方形到服务器端,准备响应
 *
 *                          public void destroy() :服务器正常关闭,过滤器销毁...
 *
 *
 *
 */
public class MyFirstFilter implements Filter {
    String encoding ;

    //无参构造方法
    public MyFirstFilter(){
        System.out.println("过滤器对象被创建了....");
    }

    public void init(FilterConfig config) throws ServletException {
        System.out.println("MyFirstFilter.init()方法====>被调用了....");
         encoding = config.getInitParameter("encoding");
        System.out.println(encoding);

    }

    //过滤任务
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request  = (HttpServletRequest) req;
        String method = request.getMethod();
        System.out.println(method);
        System.out.println("MyFirstFilter.doFilter()方法=====>被调用了");
        chain.doFilter(req, resp);//放行...

        //获取请求对象
        HttpServletResponse response = (HttpServletResponse) resp;
        response.setContentType("text/html;charset='"+encoding+"'");
        response.getWriter().write("响应成功");
    }

    public void destroy() {
        System.out.println("MyFirstFilter.destory()====>被调用了...");
    }




}
